package com.example.demo.service.impl;


import ch.qos.logback.core.pattern.util.RegularEscapeUtil;
import com.example.demo.dao.CertificateDao;
import com.example.demo.dao.RegisterDao;
import com.example.demo.entity.CertificateEneity;
import com.example.demo.entity.RegisterEntity;
import com.example.demo.result.Result;
import com.example.demo.result.ResultUtil;
import com.example.demo.service.CertificateService;
import com.example.demo.util.EndDateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
public class CertificateServiceImpl implements CertificateService {


    @Autowired
    private CertificateDao certificateDao;

    @Autowired
    private RegisterDao registerDao;

    @Override
    public Result certificate(String serialNumber ,String username) {
        if(certificateDao.selectMsg(serialNumber) == null){
            LocalDateTime localDateTime = LocalDateTime.now();
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
            RegisterEntity registerEntity = registerDao.selectDataById(serialNumber);
            CertificateEneity certificateEneity = new CertificateEneity();
             certificateEneity.setAge(registerEntity.getAge());
             certificateEneity.setIndustry(registerEntity.getIndustry());
             certificateEneity.setName(registerEntity.getName());
             certificateEneity.setRegisterDate(localDateTime.format(dateTimeFormatter));
             certificateEneity.setSerialNumber(serialNumber);
             certificateEneity.setSex(registerEntity.getSex());
             certificateEneity.setOperator(username);
             certificateEneity.setExpirationDate(EndDateUtil.getExpirationDate(certificateEneity.getRegisterDate()));
                certificateDao.certificate(certificateEneity);
                String URL = "http://47.92.204.3:8080/page?id="+serialNumber;
                registerDao.successCertify(certificateEneity.getSerialNumber());
                registerDao.afterCertificate(EndDateUtil.getExpirationDate(certificateEneity.getRegisterDate()),serialNumber);
                return ResultUtil.success(URL);
            } else {
                return ResultUtil.exists();
            }
    }
    @Override
    public CertificateEneity queryCertificate(String serialNumber) {

        return certificateDao.queryCertificate(serialNumber);
    }
}
